package spoon.bet365.service;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import spoon.bet365.domain.Game;
import spoon.bet365.domain.League;
import spoon.domain.Betting;

@Service
@Qualifier("bet365AmericanFootballService")
public class Bet365AmericanFootballService extends Bet365ServiceImpl {

	@Value("${bet365.americanFootball.url}")
	private String connectionUrl;

	@Value("${bet365.americanFootball.item}")
	private String item;

	@Value("${bet365.americanFootball.name}")
	private String itemName;

	/**
	 * 미식축구
	 */
	@Override
	public List<League> getLeague() {

		log.info("===================================================================");
		log.info("    Bet365 {} 리그 정보 검색 시작", itemName);

		List<League> leagueList = new ArrayList<League>();
		boolean isValid = false;
		String national = null;
		int leagueCnt = 0;

		String source = httpService.getSource(connectionUrl);
		StringTokenizer line = new StringTokenizer(source, "|");

		while (line.hasMoreElements()) {
			String token = line.nextToken();

			if (token.startsWith("EV")) {
				// EV 에서 NA endWith가 Lines인것만 뽑아 오자
				national = getTokenName(token, "NA");
				if (national.endsWith("Lines")) {
					isValid = true;
				}
			}

			if (isValid && token.startsWith("PA") && token.contains("NA=Game Lines")) {
				League league = new League();
				league.setItem(item);
				league.setItemName(itemName);
				league.setLeague(national);
				league.setNational(national);
				league.setGameId(getTokenName(token, "ID"));
				league.setLink(getTokenName(token, "PD"));
				leagueList.add(league);
				leagueCnt++;
			}
		}

		log.info("    Bet365 {} 리그 정보 검색 종료. 전체 추가 리그수 = {}", itemName, leagueCnt);
		log.info("===================================================================");

		return leagueList;
	}

	/**
	 * 리그별 경기
	 */
	@Override
	@Async
	public void getGame(League league) {

		long startTime = System.currentTimeMillis();

		int gameCnt = 0;
		int bettingCnt = 0;

		String url = getGameLink(league.getLink());
		league.setLink(url);

		// 리그별 게임 가져오기
		this.getGameList(league);

		// 데이터 입력
		bettingCnt = addBetting(league);
		gameCnt = league.getGameList().size();

		log.info("   사이트: {}, 종목: {}, 국가: {}, 리그: {}, 경기수: {}, 베팅수: {}, 소요시간: {}초", league.getSite(), league.getItem(), league.getNational(),
				league.getLeague(), gameCnt, bettingCnt, (System.currentTimeMillis() - startTime) / 1000.0f);
	}

	/**
	 * 리그별 게임 가져오기
	 * 
	 * @param league
	 * @return
	 */
	@Override
	protected void getGameList(League league) {
		Game game;

		// 경기시간, 팀영, 승, 무, 패배당, 링크 구분자
		int order = 0;

		List<String> dateList = new ArrayList<String>();
		List<String> teamList = new ArrayList<String>();
		List<String> handicapList = new ArrayList<String>();
		List<String> overUnderList = new ArrayList<String>();
		List<String> winLoseList = new ArrayList<String>();
		List<String> linkList = new ArrayList<String>();

		String source = httpService.getSource(league.getLink());
		StringTokenizer line = new StringTokenizer(source, "|");

		while (line.hasMoreElements()) {
			String token = line.nextToken();

			if (token.startsWith("CO")) {
				order++;
			}

			if (token.startsWith("PA")) {
				switch (order) {
				case 1: // 경기시간 1줄
					dateList.add(token);
					break;
				case 3: // 팀명 2줄
					teamList.add(token);
					break;
				case 4: // Spread (핸디캡) 2줄 없는 경우 NA가 없다
					handicapList.add(token);
					break;
				case 5: // Totals (Over/Under) 없는 경우 NA가 없다
					overUnderList.add(token);
					break;
				case 6: // Money Line (승패) 없는 경우 NA가 없다
					winLoseList.add(token);
					break;
				case 7: // 링크
					linkList.add(token);
					break;
				default:
					break;
				}
			}
		}

		for (int i = 0; i < dateList.size(); i++) {
			game = new Game();

			// 날짜
			game.setGameDate(convertDate(getTokenName(dateList.get(i), "NA")));
			// 팀명

			game.setHomeTeam(getTokenName(teamList.get(i * 2), "NA"));
			game.setAwayTeam(getTokenName(teamList.get(i * 2 + 1), "NA"));

			// Spread 핸디캡
			if (handicapList.get(i * 2).contains("OD=")) {
				String home = handicapList.get(i * 2);
				String away = handicapList.get(i * 2 + 1);

				Betting betting = new Betting();
				betting.setBettingScore("Goals");
				betting.setBettingType("1-2");
				betting.setBettingSet("Full Time");
				betting.setBettingCode("Handicap");
				betting.setBettingName("Spread");
				
				getMainGame(home, away, betting);
				game.getBettingList().add(betting);
			}

			// Totals 오버/언더
			if (overUnderList.get(i * 2).contains("OD=")) {
				String home = overUnderList.get(i * 2);
				String away = overUnderList.get(i * 2 + 1);

				Betting betting = new Betting();
				betting.setBettingScore("Goals");
				betting.setBettingType("1-2");
				betting.setBettingSet("Full Time");
				betting.setBettingCode("Over/Under");
				betting.setBettingName("Totals");
				getMainGame(home, away, betting);
				game.getBettingList().add(betting);
			}

			// Money Line 승패
			if (winLoseList.get(i * 2).contains("OD=")) {
				String home = winLoseList.get(i * 2);
				String away = winLoseList.get(i * 2 + 1);

				Betting betting = new Betting();
				betting.setBettingScore("Goals");
				betting.setBettingType("1-2");
				betting.setBettingSet("Full Time");
				betting.setBettingCode("1-2");
				betting.setBettingName("Money Line");
				getMainGame(home, away, betting);
				game.getBettingList().add(betting);
			}

			// 게임설정 완료
			if (game.getBettingList().size() > 0) {
				league.getGameList().add(game);
			}
		}
	}

	@Override
	protected void getBettingList(Game game) {
		// 배구는 추가 정보를 가져올 필요가 없다.
	}

}
